package com.android.hw.projectmenu;

import com.android.hw.projectmenu.IVibratorBackService.Stub;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;



public class VibratorCtrl extends Activity implements OnClickListener, OnCheckedChangeListener {
	final static String TAG="hytest/VibratorCtrl";
	private Context mContext;
	private IVibratorBackService.Stub vibrator;
	private EditText cyclePauseView;
	private EditText cycleVibrateView;
	private EditText delayView;
	private EditText hourView;
	private EditText minuteView;
	private EditText secondView;
	private TextView infoView;
	private RadioGroup group;
	private int cyclePause;
	private int cycleVibrate;
	private long tarTime;
	private boolean noStop=false;
	final int DEFAULT_VIBRATE_PERIOD=5;
	private Handler mHandler= new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vibrator_ctrl);
		mContext = this;
		if(vibrator== null){
			Intent intent=new Intent();
			intent.setClass(this, VibratorBackService.class);
			this.startService(intent);
			this.bindService(intent, conn, Context.BIND_AUTO_CREATE);
		}
		
		cyclePauseView = (EditText) this.findViewById(R.id.cycle_pause);
		cycleVibrateView=(EditText) this.findViewById(R.id.cycle_vibrate);
		delayView=(EditText) this.findViewById(R.id.vibrate_delay);
		hourView=(EditText) this.findViewById(R.id.hour);
		minuteView=(EditText) this.findViewById(R.id.minute);
		secondView=(EditText) this.findViewById(R.id.second);
		infoView = (TextView) this.findViewById(R.id.info);
		group=(RadioGroup) this.findViewById(R.id.group);
		group.setOnCheckedChangeListener(this);

		
		Button bt_start=(Button) this.findViewById(R.id.vb_start);
		bt_start.setOnClickListener(this);

		Button bt_stop=(Button) this.findViewById(R.id.vb_stop);
		bt_stop.setOnClickListener(this);
	}
	
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mHandler.removeCallbacks(updateStateRunnable);

	}


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mHandler.post(updateStateRunnable);
	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		this.unbindService(conn);
		super.onDestroy();
		
	}


	/**
	 * init view state from the server
	 */
	void updateView(){
		int mDelay;
		int mHour;
		int mMinu;
		int mSecond;
		boolean nostop = false;
		
		try {
			int[] data = vibrator.getCycle();
			cycleVibrate=data[0]/1000;
			cyclePause = data[1]/1000;
			nostop = vibrator.isNoStop();
			tarTime=vibrator.getTime();
			long lefttime=(tarTime-System.currentTimeMillis())/1000;
			if(lefttime>=0){
				mHour = (int) (lefttime/3600);
				mMinu  = (int) ((lefttime%3600)/60);
				mSecond=(int) (lefttime%60);
			}else{
				mHour = 0;
				mMinu = 0;
				mSecond = 0;
			}
			
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			cycleVibrate = DEFAULT_VIBRATE_PERIOD;
			cyclePause = 0;
			nostop = false;
			mHour = 0;
			mMinu = 0;
			mSecond = 0;
			
		}
		mDelay = 0;
		
		cycleVibrateView.setText(""+cycleVibrate);
		cyclePauseView.setText(""+cyclePause);
		delayView.setText(""+mDelay);
		hourView.setText(""+mHour);
		minuteView.setText(""+mMinu);
		secondView.setText(""+mSecond);
		
		if(nostop){
			group.check(R.id.no_stop);
			delayView.setEnabled(false);
			hourView.setEnabled(false);
			minuteView.setEnabled(false);
			secondView.setEnabled(false);
		}else{
			group.check(R.id.vibrate_cycle);
			delayView.setEnabled(true);
			hourView.setEnabled(true);
			minuteView.setEnabled(true);
			secondView.setEnabled(true);
		}			

		updateInfo();
	};
	
	void updateInfo(){
		if(vibrator != null){
			try {
				int[] data = vibrator.getCycle();
				boolean nostop = vibrator.isNoStop();
				long tartime=vibrator.getTime();
				StringBuilder sb = new StringBuilder();
				if(nostop || 
						(!nostop && tartime-System.currentTimeMillis()>0)){
					sb.append(mContext.getString(R.string.state_started));
					sb.append("\n");
					
					sb.append(mContext.getString(R.string.cycle_vibrate));
					sb.append(":");
					sb.append(data[0]/1000);
					sb.append("\n");

					sb.append(mContext.getString(R.string.cycle_pause));
					sb.append(":");
					sb.append(data[1]/1000);
					sb.append("\n");
					
					sb.append(mContext.getString(R.string.left_time));
					if(nostop){
						sb.append(mContext.getString(R.string.vibrate_no_stop));
					}else{
						tarTime=vibrator.getTime();
						long lefttime=(tarTime-System.currentTimeMillis())/1000;
						if(lefttime > 0){
							int hour = (int) (lefttime/3600);
							int minu  = (int) ((lefttime%3600)/60);
							int second=(int) (lefttime%60);
							sb.append(hour);
							sb.append(mContext.getString(R.string.hour));
							sb.append(minu);
							sb.append(mContext.getString(R.string.minute));
							sb.append(second);
							sb.append(mContext.getString(R.string.second));	
						}
					}
					
				}else{
					sb.append(mContext.getString(R.string.state_stoped));
				}
				
				infoView.setText(sb.toString());
				
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				infoView.setText("");
			}
		}
	}
	
	private Runnable updateStateRunnable=new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			
			updateInfo();
			mHandler.postDelayed(updateStateRunnable,1000);
		}
		
	};
	
	
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		int id = arg0.getId();
		if(R.id.vb_start==id){
			doStart();
		}else if(R.id.vb_stop==id){
			try {
				vibrator.stop();
				updateView();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * check the edit before start
	 */
	void doStart(){
		int mDelay;
		int mHour;
		int mMinu;
		int mSecond;
		
		String  pauseString = cyclePauseView.getText().toString();
		if(pauseString == null || pauseString.length()==0){
			cyclePause=0;
			cyclePauseView.setText("0");
		}else{
			cyclePause = Integer.parseInt(pauseString)*1000;
		}

		String  vibrateString = cycleVibrateView.getText().toString();
		if(vibrateString == null || vibrateString.length()==0){
			cycleVibrate=DEFAULT_VIBRATE_PERIOD;
			cycleVibrateView.setText(""+DEFAULT_VIBRATE_PERIOD);
		}else{
			cycleVibrate = Integer.parseInt(vibrateString)*1000;
		}
		
		
		long time;
		if(!noStop){
			String  delayString = delayView.getText().toString();
			if(delayString == null || delayString.length()==0){
				mDelay=0;
				delayView.setText("0");
			}else{
				mDelay = Integer.parseInt(delayString)*1000;
			}
			
			String  hourString = hourView.getText().toString();
			if(hourString == null || hourString.length()==0){
				mHour=0;
				hourView.setText("0");
			}else{
				mHour = Integer.parseInt(hourString);
			}
			
			String  minuString = minuteView.getText().toString();
			if(minuString == null || minuString.length()==0){
				mMinu=0;
				minuteView.setText("0");
			}else{
				mMinu = Integer.parseInt(minuString);
			}
			
			String  secondString = secondView.getText().toString();
			if(secondString == null || secondString.length()==0){
				mSecond=0;
				secondView.setText("0");
			}else{
				mSecond = Integer.parseInt(secondString);
			}
			time = (mHour*3600+mMinu*60+mSecond)*1000;
			if(time < cycleVibrate+cyclePause){
				pupDialog();
				return;
			}
		}else{
			time = 0;
			mDelay = 0;
		}

		
		try {
			vibrator.setCycle(cycleVibrate, cyclePause);
			
			if(noStop){
				vibrator.vibrate(0,0);
			}else{
				vibrator.vibrate(mDelay,time);
			}
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		updateView();
	}
	
	
	/**
	 * 
	 */
	private void pupDialog(){

		AlertDialog alertDialog = new AlertDialog.Builder(this). 
                setTitle(R.string.vibrator_ctrl). 
                setMessage(R.string.vibrate_warning). 
                setPositiveButton("OK", null).
                create(); 
        alertDialog.show(); 
    
	}
	/**
	 * 
	 */
	ServiceConnection conn=new ServiceConnection(){

		@Override
		public void onServiceConnected(ComponentName arg0, IBinder arg1) {
			// TODO Auto-generated method stub
			Log.d(TAG, "onServiceConnected");
			vibrator=(IVibratorBackService.Stub) arg1;
			
			updateView();
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			// TODO Auto-generated method stub
			Log.d(TAG, "onServiceDisconnected");
			mHandler.removeCallbacks(updateStateRunnable);
			vibrator=null;
		}
		
	};

	@Override
	public void onCheckedChanged(RadioGroup arg0, int arg1) {
		// TODO Auto-generated method stub
		if(arg1==R.id.no_stop){
			noStop = true;
			delayView.setEnabled(false);
			hourView.setEnabled(false);
			minuteView.setEnabled(false);
			secondView.setEnabled(false);
		}else if(arg1==R.id.vibrate_cycle){
			noStop = false;
			delayView.setEnabled(true);
			hourView.setEnabled(true);
			minuteView.setEnabled(true);
			secondView.setEnabled(true);
		}
	}


	

}